package org.kl.bf.web.basic;

import java.util.List;
import java.util.Map;

import javax.servlet.ServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.kl.bf.entity.basic.CodeValues;
import org.kl.bf.entity.basic.ExcelConfig;
import org.kl.bf.entity.basic.ExcelImport;
import org.kl.bf.entity.easyui.EasyuiUtils;
import org.kl.bf.repository.basic.CodeValuesDao;
import org.kl.bf.service.basic.ExcelConfigService;
import org.kl.bf.service.basic.ExcelImportService;
import org.kl.bf.utils.BasicConstants;
import org.kl.bf.utils.KLServlets;
import org.kl.bf.web.base.BasicController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.MediaTypes;

/**
 * 
 * @Author hqm
 * @CreateTime 2014-3-13 下午9:34:36
 */
@Controller
@RequestMapping(value = "/basic/excelConfig")
public class ExcelConfigController extends BasicController {
	@Autowired
	private ExcelConfigService excelConfigService;

	@Autowired
	private ExcelImportService excelImportService;
	@Autowired
	private CodeValuesDao codeValuesDao;

	@RequiresPermissions("excelImport:list")
	@RequestMapping(method = RequestMethod.GET)
	public String list() {
		return "basic/excelConfigList";
	}

	@RequiresPermissions("excelImport:list")
	@RequestMapping(value = "dataGrid", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String dataGrid(@RequestParam(value = "pageNumber", defaultValue = "1") int pageNumber,
			@RequestParam(value = "rows", defaultValue = PAGE_SIZE) int pageSize,
			@RequestParam(value = "sort", defaultValue = "columnNo") String sortType,
			@RequestParam(value = "order", defaultValue = "asc") String orderType, Model model, ServletRequest request) {
		Page<ExcelConfig> excelConfigs;
		/*
		 * if
		 * (StringUtils.isBlank(request.getParameter("search_EQ_excelImportId"
		 * ))) { excelConfigs = new PageImpl<ExcelConfig>(new
		 * ArrayList<ExcelConfig>()); } else {
		 */
		Map<String, Object> searchParams = KLServlets.getParametersStartingWith(request, SEARCH_PREFIX);
		excelConfigs = excelConfigService.getUserExcelConfig(searchParams, pageNumber, pageSize, sortType, orderType);
		return EasyuiUtils.buildEasyuiGridJsonString(excelConfigs.getContent(), (int) excelConfigs.getTotalElements());
	}

	@RequiresPermissions("excelImport:update")
	@RequestMapping(value = "update", method = RequestMethod.POST, produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String update(@Valid @ModelAttribute("excelConfig") ExcelConfig excelConfig,
			@RequestParam(value = "javaType", defaultValue = "-1") String javaType, String excelImport,
			RedirectAttributes redirectAttributes) {
		CodeValues cv = codeValuesService.getCodeValues(javaType);
		ExcelImport ei = excelImportService.getExcelImport1(excelImport);
		excelConfig.setCodeValues(cv);
		excelConfig.setExcelImport(ei);
		excelConfigService.saveExcelConfig(excelConfig);
		return ajaxMsg("编辑成功", true, null);
	}

	@RequiresPermissions("excelImport:delete")
	@RequestMapping(value = "delete/{id}", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String delete(@PathVariable("id") String id, RedirectAttributes redirectAttributes) {
		excelConfigService.deleteExcelConfig(id);
		return ajaxMsg("删除成功", true, null);
	}

	@RequiresPermissions("excelImport:delete")
	@RequestMapping(value = "multiDelete", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String multiDelete(@RequestParam(value = "ids", defaultValue = "") String ids) {
		String msg = "";
		try {
			msg = excelConfigService.multiDelete(ids);
		} catch (Exception e) {
			e.printStackTrace();
			return ajaxMsg("删除失败:" + e.getMessage(), false, null);
		}
		return ajaxMsg("删除成功:" + msg, true, null);
	}

	@RequiresPermissions("excelImport:bulid")
	@RequestMapping(value = "bulid", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String bulid(@RequestParam(value = "id", defaultValue = "1") String id, RedirectAttributes redirectAttributes,
			HttpSession session) {
		String[] jdbcPath = new String[4];
		jdbcPath[0] = (String) session.getServletContext().getAttribute(BasicConstants.JDBC_DRIVER);
		jdbcPath[1] = (String) session.getServletContext().getAttribute(BasicConstants.JDBC_URL);
		jdbcPath[2] = (String) session.getServletContext().getAttribute(BasicConstants.JDBC_USERNAME);
		jdbcPath[3] = (String) session.getServletContext().getAttribute(BasicConstants.JDBC_PASSWORD);
		String msg = "";
		try {
			msg = excelConfigService.bulid(id, session);
		} catch (Exception e) {
			e.printStackTrace();
			return ajaxMsg("生成失败:" + e.getMessage(), false, null);
		}
		return ajaxMsg("自动生成成功," + msg, true, null);
	}

	/**
	 * 通用查改增删，用于行编辑表格(表格式录入)
	 * 
	 * @return
	 */
	@RequiresPermissions(value = "excelImport:update")
	@RequestMapping(value = "crud", method = RequestMethod.POST, produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String crud(@RequestParam(value = "inserted") String inserted, @RequestParam(value = "updated") String updated,
			@RequestParam(value = "deleted") String deleted, RedirectAttributes redirectAttributes) {
		try {
			excelConfigService.crud(inserted, updated, deleted);
			return ajaxMsg("保存成功", true, null);
		} catch (Exception e) {
			e.printStackTrace();
			return ajaxMsg("保存失败:<br>" + e.getMessage(), false, null);
		}
	}

	/**
	 * 树形下拉框
	 * 
	 * @param sortType
	 * @param orderType
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "comboTreeJavaType", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String comboTreeJavaType(Model model, ServletRequest request) {
		return jsonCodeValuesByTableNo(BasicConstants.TableNo_JAVATYPE);
	}

	/**
	 * 下拉框
	 * 
	 * @param model
	 * @param request
	 * @return
	 */
	@RequestMapping(value = "comboboxJavaType", produces = MediaTypes.JAVASCRIPT_UTF_8)
	@ResponseBody
	public String comboboxJavaType() {
		List<CodeValues> codeValues = codeValuesService.findByTableId(BasicConstants.TableNo_JAVATYPE, 0);
		return jsonMapper.toJson(codeValues);
	}

	/**
	 * 所有RequestMapping方法调用前的Model准备方法, 实现Struts2
	 * Preparable二次部分绑定的效果,先根据form的id从数据库查出Task对象,再把Form提交的内容绑定到该对象上。
	 * 因为仅update()方法的form中有id属性，因此仅在update时实际执行.
	 */
	@ModelAttribute
	public void getExcelConfig(@RequestParam(value = "id", defaultValue = "-1") String id, Model model) {
		if (!id.equals("-1")) {
			model.addAttribute("excelConfig", excelConfigService.getExcelConfig(id));
		}
	}
}
